
import { PrismaService } from 'src/modules/prisma.service';
import { Controller, Body, Param, Delete, Get, Post, Put, Query, Headers } from '@nestjs/common';
import { UserAddDto, UserAddZod, UserEditDto } from 'src/types/dtoExt/User.dto';
import { filterUndefined, parseCookie, safeParse } from 'src/utils';
import { UserService } from './user.service';
import { z } from 'zod';
import { UserVo, UserVoZod } from 'src/types/vo/User.vo';
import { ApiExtraModels } from '@nestjs/swagger';
import { ApiJsonResponse, ApiPaginationResponse, ApiSuccessResponseDto, EmptyData, Pagination } from 'src/decorator/swagger';
import { UserInsertZod } from 'src/types/entrity/User.dto';
import { verifyCodeSessionIdMap } from 'src/store';

@ApiExtraModels(EmptyData) // 注入基础模型
@ApiExtraModels(Pagination) // 注入基础模型
@ApiExtraModels(ApiSuccessResponseDto) // 注入基础模型
@Controller('user')
export class UserController {
  constructor(
    private readonly mysql: PrismaService,
    private readonly userService: UserService
  ) {}
  
  @Post()
  @ApiJsonResponse(EmptyData, { desc: '用户注册' })
  async createUser(
    @Body() _data: UserAddDto,
    @Headers('cookie') cookie,
  ) {
    const data = safeParse(UserAddZod, _data);

    if (data.inviteCode !== 'lammu2024') {
      return {
        code: -1,
        message: '邀请码不正确',
      }
    }

    if (data.verifyCode && verifyCodeSessionIdMap[parseCookie(cookie).verifyCodeSessionId] !== data.verifyCode.toLowerCase()) {
      return {
        code: -1,
        message: '验证码不正确或已过期',
      }
    }

    if (await this.userService.getUserByEmail(data.email)) {
      return {
        code: -1,
        message: '账号已存在',
      }
    }
    await this.userService.insertUser(safeParse(UserInsertZod, {
      ...data,
      psw: this.userService.getHash(this.userService.aesDecode(data.psw)), // aes加密后的密码
    }));
  }

  @Delete('/:id')
  async deleteUser(@Param('id') _id: string) {
    const id = Number(_id);
    await this.mysql.user.update({
      where: { id },
      data: { isDeleted: true }
    });
  }

  @Get()
  @ApiPaginationResponse(UserVo, {desc: '分页获取用户'})
  async findPageUser(@Query() query: any) {
    const userList = await this.mysql.user.findMany({
      where: filterUndefined({
        isDeleted: false,
        nickName: !query.nickName ? undefined : {
          contains: query.nickName
        },
        realName: !query.realName ? undefined : {
          contains: query.realName
        },
        sex: !query.sex ? undefined : Number(query.sex)
      }),
      take: Number(query.pageSize || 10),
      skip: (Number(query.current || 1) - 1 ) * Number(query.pageSize || 10),
    });
    const totalCount = await this.mysql.user.count({
      where: {
        isDeleted: false,
      },
    });

    return {
      list: z.array(UserVoZod).parse(userList),
      pageSize: Number(query.pageSize || 10),
      currentPage: Number(query.currentPage || 1),
      totalCount,
    };
  }

  @Put('/:id')
  async updateUser(
    @Param('id') _id: string,
    @Query('action') action: 'updateEnable',
    @Body() data: UserEditDto
  ) {
    const id = Number(_id);
    delete (data as any).id;
    delete (data as any).isDeleted;
    if (action === 'updateEnable') {
      await this.mysql.user.update({
        where: {
          id
        },
        data: {
          isEnable: data.isEnable
        }
      })
    } else {
      await this.mysql.user.update({
        where: {
          id
        },
        data: filterUndefined(data)
      })
    }
    
  }
}
